package com.ym.pms.controller;

import com.alibaba.fastjson.JSON;
import com.ym.pms.dto.MessageDTO;
import com.ym.pms.utils.JSONResult;
import com.ym.pms.utils.RedisUtils;
import com.ym.pms.utils.SmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: xybh
 * @Description: 短信验证接口
 * @Date: Created in 10:47 2020/12/4
 * @Modified:
 */
@RestController
@Api(tags = "短信验证接口")
@RequestMapping("/sms")
//@CrossOrigin
public class MessageController {
    @RequestMapping(value = "/send", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "发送验证短信")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "phone", value = "手机号", required = true)
    )
    public JSONResult sendMessage(@RequestParam("phone") String phone) {
        String res = SmsUtil.sendMessage(phone);
        MessageDTO messageDTO = JSON.parseObject(res, MessageDTO.class);
        String otp = messageDTO.getOtp();
        if (otp == null){
            return JSONResult.errorMsg("验证码请求过快!");
        }
        //将验证码存入Redis
        RedisUtils.set("sms-" + phone, otp, 10 * 60);
        return JSONResult.ok();
    }

    @PostMapping("/verify")
    @ApiOperation(value = "验证验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号"),
            @ApiImplicitParam(name = "ticket", value = "验证码")
    })
    public JSONResult verifyMessage(@RequestParam String phone,
                                    @RequestParam String ticket) {
        String vt = (String) RedisUtils.get("sms-" + phone);
        if (StringUtils.isEmpty(vt) || !ticket.equals(vt)) {
            return JSONResult.build(401, "验证码错误", "");
        } else {
            return JSONResult.ok();
        }

    }
}
